import React from "react";
import type { FC, CSSProperties } from "react";
import classNames from "classnames";
import { AiFillCheckCircle, AiFillCloseCircle } from "react-icons/ai";
import { validProgress } from "./utils";
import styles from "./style.module.css";

export type ProgressStatus = "success" | "exception" | "normal" | "active";

export interface ProgressState {
  width?: number | string;
  height?: number | string;
  /** 百分比 */
  percent?: number;
  /** 状态，可选：success exception normal active(仅限 line) */
  status?: ProgressStatus;
  /** 是否显示进度数值或状态图标 */
  showInfo?: boolean;
  /** 保留几位小数 */
  toFixed?: number;
  style?: CSSProperties;
}

export const Progress: FC<ProgressState> = React.memo(
  ({
    percent = 0,
    width = 320,
    height = 8,
    status = "success",
    showInfo = true,
    toFixed = 0,
    style,
  }) => {
    const percentNumber = React.useMemo<number>(() => {
      return validProgress(Number(percent.toFixed(toFixed)));
    }, [percent]);

    const progressStatus = React.useMemo<ProgressState["status"]>(() => {
      if (status !== "exception" && percentNumber >= 100) {
        return "success";
      }
      return status || "normal";
    }, [status, percentNumber]);

    const progressInfo = React.useMemo(() => {
      if (!showInfo) {
        return null;
      }
      let text: React.ReactNode;
      if (progressStatus !== "exception" && progressStatus !== "success") {
        text = `${percentNumber}%`;
      } else if (progressStatus === "exception") {
        text = (
          <AiFillCloseCircle
            className={styles["varan-progress-icons"]}
            style={{
              color: "var(--varan-progress-exception-color)",
              display: "flex",
            }}
          />
        );
      } else if (progressStatus === "success") {
        text = (
          <AiFillCheckCircle
            className={styles["varan-progress-icons"]}
            style={{
              color: "var(--varan-progress-success-color)",
              display: "flex",
            }}
          />
        );
      }
      return (
        <span className={classNames(styles["varan-progress-text"])}>
          {text}
        </span>
      );
    }, [percentNumber, progressStatus]);

    return (
      <div
        style={{ width, ...style }}
        className={classNames(styles["varan-progress"])}>
        <div
          className={classNames(styles["varan-progress-inner"])}
          style={{ height }}>
          <div
            style={{ width: percentNumber + "%" }}
            className={classNames(
              styles["varan-progress-item"],
              styles[`varan-progress-item-${progressStatus}`]
            )}></div>
        </div>
        {progressInfo}
      </div>
    );
  }
);
